<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <el-input
          v-model="deptName"
          placeholder="请输入组织名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />

        <el-tree
          :data="deptOptions"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          ref="tree"
          default-expand-all
          @node-click="handleNodeClick"
        />
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="所属类型" prop="dictTypeId">
            <el-select v-model="queryParams.dictCode"
                       clearable
                       size="small"
            >
              <el-option v-for="dictData in thirdDictDataOptions"
                         :key="dictData.dictCode"
                         :label="dictData.dictLabel"
                         :value="dictData.dictCode"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="状态"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                       v-hasPermi="['baseData:thirdData:query']"
            >搜索
            </el-button>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-hasPermi="['baseData:thirdData:add']"
            >新增
            </el-button>
            <el-button type="warning" icon="el-icon-download" size="mini" v-hasPermi="['baseData:thirdData:export']"
                       @click="handleExport"
            >导出
            </el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="dataList" border>
          <el-table-column label="所属组织" align="center" prop="deptName" min-width="120"/>
          <el-table-column label="数据类型" align="center" prop="dictLabel" min-width="120"/>
          <el-table-column label="企业账号" align="center" prop="companyMobile" min-width="120"/>
          <el-table-column label="key" align="center" prop="dataKey" :show-overflow-tooltip="true"/>
          <el-table-column label="secret" align="center" prop="secret" :show-overflow-tooltip="true"/>
          <el-table-column label="uri_activity" align="center" prop="uriActivity" min-width="100"
                           :show-overflow-tooltip="true"
          />
          <el-table-column label="uri_action" align="center" prop="uriAction" min-width="100"
                           :show-overflow-tooltip="true"
          />
          <el-table-column label="模板ID" align="center" prop="templateId" :show-overflow-tooltip="true"/>
          <el-table-column label="账号" align="center" prop="account" :show-overflow-tooltip="true"/>
          <el-table-column label="密码" align="center" prop="password" :show-overflow-tooltip="true"/>
          <el-table-column label="邓白氏编号" align="center" prop="dbsCode" min-width="100" :show-overflow-tooltip="true"/>
          <el-table-column v-if="false" label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
          <el-table-column v-if="false" label="显示顺序" align="center" prop="orderNum"/>
          <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" width="100"/>
          <el-table-column label="操作" align="center" width="150px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['baseData:thirdData:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['baseData:thirdData:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :before-close="closeDialogConfirm">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属组织" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true"
                          placeholder="请选择归属组织"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="数据类型" prop="dictCode">
              <el-select v-model="form.dictCode"
                         size="small"
                         @change="handleSelectDictCodeChange"
              >
                <el-option v-for="dictData in thirdDictDataOptions"
                           :key="dictData.dictCode"
                           :label="dictData.dictLabel"
                           :value="dictData.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" v-if="showCompanyMobile(form.dictCode)">
            <el-form-item label="企业账号" prop="companyMobile">
              <el-input v-model="form.companyMobile" placeholder="企业账号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showDataKey(form.dictCode)">
            <el-form-item label="key" prop="dataKey">
              <el-input v-model="form.dataKey" placeholder="请输入key"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showSecret(form.dictCode)">
            <el-form-item label="secret" prop="secret">
              <el-input v-model="form.secret" placeholder="请输入secret"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showUriActivity(form.dictCode)">
            <el-form-item label="uri_activity" prop="uriActivity">
              <el-input v-model="form.uriActivity" placeholder="请输入uri_activity"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showUriAction(form.dictCode)">
            <el-form-item label="uri_action" prop="uriAction">
              <el-input v-model="form.uriAction" placeholder="uri_action"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showTemplateId(form.dictCode)">
            <el-form-item label="模板ID" prop="templateId">
              <el-input v-model="form.templateId" placeholder="请输入模板ID"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showAccount(form.dictCode)">
            <el-form-item label="账号" prop="account">
              <el-input v-model="form.account" placeholder="账号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showPassword(form.dictCode)">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="密码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="showDbsCode(form.dictCode)">
            <el-form-item label="邓白氏编号" prop="dbsCode">
              <el-input v-model="form.dbsCode" placeholder="请输入邓白氏编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addThirdData,
  delThirdData,
  exportThirdData,
  getDictDataByType,
  listThirdData,
  updateThirdData
} from '@/api/system/dict'
import { deptTreeSelect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Data',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      dataList: [],
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      // 字典类型
      thirdDictDataOptions: [],
      selectedOrgCode: '',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictCode: undefined,
        dataKey: undefined,
        secret: undefined,
        deptId: undefined,
        uriActivity: undefined,
        uriAction: undefined,
        templateId: undefined,
        account: undefined,
        password: undefined,
        dbsCode: undefined,
        orderNum: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dictCode: [
          { required: true, message: '所属数据类型不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '所属组织不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
    getDictDataByType('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    getDictDataByType('sys_third').then(response => {
      this.thirdDictDataOptions = response.data
    })
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    /** 查询第三方列表 */
    getList() {
      this.loading = true
      listThirdData(this.queryParams).then(response => {
        this.dataList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },

    // 筛选组织书节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    // 组织树节点单击事件
    handleNodeClick(data) {
      this.selectedOrgCode = data.id
      this.queryParams.deptId = data.id
      this.getList()
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dictCode: undefined,
        dataKey: undefined,
        secret: undefined,
        deptId: undefined,
        companyMobile: undefined,
        uriActivity: undefined,
        uriAction: undefined,
        templateId: undefined,
        account: undefined,
        password: undefined,
        dbsCode: undefined,
        delFlag: undefined,
        remark: undefined,
        orderNum: undefined,
        status: '0',
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 若没有选中组织, 则赋予默认值, 即顶层组织
      if (this.selectedOrgCode === '') {
        this.selectedOrgCode = this.deptOptions[0].id
      }
      this.form.deptId = this.selectedOrgCode
      this.form.orderNum = 1

      this.open = true
      this.title = '添加第三方数据'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = JSON.parse(JSON.stringify(row))
      this.open = true
      this.title = '修改第三方数据'
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateThirdData(this.filterFormData(this.form)).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addThirdData(this.filterFormData(this.form)).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delThirdData({ id: row.id })
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },

    /**
     * 对话框确认关闭
     */
    closeDialogConfirm() {
      this.$confirm('确认关闭?').then(() => {
        this.open = false
      }).catch(() => {
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return exportThirdData(this.queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },

    // 对话框修改数据类型, 则需要相应显示表单项
    handleSelectDictCodeChange(value) {
      console.log(value)
    },

    // 是否显示企业手机号, 极光,云片IOS不显示
    showCompanyMobile(value) {
      if (!value) {
        return true
      }
      return value !== 34 && value !== 35 && value !== 43
    },

    // 是否显示key, IOS不显示
    showDataKey(value) {
      if (!value) {
        return true
      }
      return value !== 43
    },

    // 是否显示secret, 云片,IOS不显示
    showSecret(value) {
      if (!value) {
        return true
      }
      return value !== 35 && value !== 43
    },

    // 是否显示uriActivity, 仅云片,萤石,IOS不显示
    showUriActivity(value) {
      if (!value) {
        return true
      }
      return value !== 35 && value !== 36 && value !== 43
    },

    // 是否显示uriAction, 仅云片,萤石,IOS不显示
    showUriAction(value) {
      if (!value) {
        return true
      }
      return value !== 35 && value !== 36 && value !== 43
    },

    // 是否显示templateId, 仅极光,萤石,IOS不显示
    showTemplateId(value) {
      if (!value) {
        return true
      }
      return value !== 34 && value !== 36 && value !== 43
    },

    // 是否显示account, 仅极光,云片,萤石不显示
    showAccount(value) {
      if (!value) {
        return true
      }
      return value !== 34 && value !== 35 && value !== 36
    },

    // 是否显示password, 仅极光,云片,萤石不显示
    showPassword(value) {
      if (!value) {
        return true
      }
      return value !== 34 && value !== 35 && value !== 36
    },

    // 是否显示邓白氏编码, 仅IOS显示
    showDbsCode(value) {
      if (!value) {
        return true
      }
      return value === 43
    },

    // 过滤多余的属性
    filterFormData(form) {
      let resultData = JSON.parse(JSON.stringify(form))
      let dictCode = resultData.dictCode

      switch (dictCode) {
        // 极光 有data_key secret uri_activity uri_action
        case 34:
          resultData.companyMobile = ''
          resultData.templateId = ''
          resultData.account = ''
          resultData.password = ''
          resultData.dbsCode = ''
          break
        // 云片 有data_key template_id
        case 35:
          resultData.companyMobile = ''
          resultData.secret = ''
          resultData.uriActivity = ''
          resultData.uriAction = ''
          resultData.account = ''
          resultData.password = ''
          resultData.dbsCode = ''
          break
        // 萤石 有company_mobile data_key secret
        case 36:
          resultData.uriActivity = ''
          resultData.uriAction = ''
          resultData.templateId = ''
          resultData.account = ''
          resultData.password = ''
          resultData.dbsCode = ''
          break
        // IOS  有account password dbs_code
        case 43:
          resultData.companyMobile = ''
          resultData.dataKey = ''
          resultData.secret = ''
          resultData.uriActivity = ''
          resultData.uriAction = ''
          resultData.templateId = ''
          break
        default:
          break
      }

      return resultData
    }
  }
}
</script>
